package com.jic.market.impl;

import com.beust.jcommander.internal.Lists;
import com.google.common.collect.Maps;
import com.jic.common.base.vo.RestResult;
import com.jic.manager.api.rest.ManagerMerchantApi;
import com.jic.manager.api.rest.ManagerStoreApi;
import com.jic.manager.request.MerchantRequest;
import com.jic.manager.response.MemStoreResponse;
import com.jic.market.PromotionUpdatePresellInfoRequest;
import com.jic.market.common.enums.DeleteFlagEnum;
import com.jic.market.common.enums.MutexFlagEnum;
import com.jic.market.common.enums.ProductScopeTypeEnum;
import com.jic.market.common.enums.TypeOfProductEnum;
import com.jic.market.common.exception.MarketException;
import com.jic.market.common.util.LoginService;
import com.jic.market.entity.*;
import com.jic.market.entity.mutex.MutexModel;
import com.jic.market.entity.mutex.MutexProductEntity;
import com.jic.market.entity.mutex.MutexResultContext;
import com.jic.market.enums.FrontPromotionTypeEnum;
import com.jic.market.enums.PromotionLimitRuleLimitTypeEnum;
import com.jic.market.enums.PromotionTypeEnum;
import com.jic.market.mapper.*;
import com.jic.market.mapper.base.BaseActivityMapper;
import com.jic.market.mapper.coupon.CouponGoodsMapper;
import com.jic.market.orm.Pagination;
import com.jic.market.request.*;
import com.jic.market.request.rest.PresellProductRequest;
import com.jic.market.response.*;
import com.jic.market.service.JicMarketPromotionService;
import com.jic.market.service.PPromotionMutexShareShipService;
import com.jic.market.service.PromotionMerchantProductService;
import com.jic.market.service.PromotionMutexService;
import com.jic.market.service.mutex.MutexService;
import com.jic.product.after.api.ProductListApi;
import com.jic.product.after.request.GoodsPageQueryRequest;
import com.jic.product.after.response.ProductStoreInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * @author ：xuyongliang
 * @date ：Created in 2020/1/16 10:02 AM
 * @description：促销商家商品服务
 * @modified By：`
 * @version: 1.0
 */
@Slf4j
@Service
public class PromotionMerchantProductServiceImpl implements PromotionMerchantProductService{

//    private final static Logger logger = LoggerFactory.getLogger(PromotionMerchantProductServiceImpl.class);

    @Resource
    private PromotionMerchantProductEntityMapper promotionMerchantProductEntityMapper;

    @Resource
    private PromotionStoreProductEntityMapper pspMapper;

    @Resource
    private PromotionEntityMapper promotionEntityMapper;

    @Resource
    private PromotionMutexMapper promotionMutexMapper;

    @Resource
    private PromotionMutexService promotionMutexService;

    @Resource
    private PPromotionMutexShareShipService pPromotionMutexShareShipService;

    @Resource
    private JicMarketPromotionService jicMarketPromotionService;

    @Resource
    private LoginService loginService;

    @Resource
    private PromotionStatusComponent promotionStatusComponent;

    @Resource
    private PromotionSingleRuleEntityMapper promotionSingleRuleEntityMapper;

    @Autowired
    PromotionLimitRuleEntityMapper promotionLimitRuleEntityMapper;

    @Autowired
    MutexService mutexService;

    @Autowired
    private ManagerMerchantApi managerMerchantApi;

    @Autowired
    private ManagerStoreApi managerStoreApi;

    @Autowired
    PromotionMerchantEntityMapper promotionMerchantEntityMapper;

    @Autowired
    private PatchGrouponMpEntityMapper patchGrouponMpEntityMapper;

    @Resource
    private ProductListApi productListApi;

    @Autowired
    private BaseActivityMapper baseActivityMapper;

    @Autowired
    private CouponGoodsMapper couponGoodsMapper;

    @Override
    public int deleteBatch(List<Long> ids) {
        if(ids == null || ids.size() == 0){
            return 0;
        }
        ids.forEach(id->{
            PromotionMerchantProductEntity merchantProductEntity = promotionMerchantProductEntityMapper.queryEntityById(id);

            PromotionMerchantProductEntity updateParam = new PromotionMerchantProductEntity();
            updateParam.setId(id);
            updateParam.setDeleteFlag(1);
            updateParam.setChannelMerchantLimit(0l);
            updateParam.setChannelStoreLimit(0l);
            updateParam.setChannelIndividualLimit(0l);
            //是否存在未删除的互斥商品
            AtomicBoolean mutexFlag = new AtomicBoolean(false);
            //删除所有sku
            if(merchantProductEntity.getTypeOfProduct() == 10){
                PromotionMerchantProductEntity productEntity = new PromotionMerchantProductEntity();
                productEntity.setMpParentId(merchantProductEntity.getMpId());
                productEntity.setDeleteFlag(0);
                productEntity.setPromotionId(merchantProductEntity.getPromotionId());
                List<PromotionMerchantProductEntity> all = promotionMerchantProductEntityMapper.findAll(productEntity);
                if(CollectionUtils.isNotEmpty(all)){
                    all.stream().forEach(x->{
                        if(MutexFlagEnum.MUTEX.getCode().equals(x.getMutexFlag())&& DeleteFlagEnum.UN_DELETE.getCode().equals(x.getDeleteFlag())){
                            mutexFlag.set(true);
                        }else{
                            deleteProductV2(x.getId());
                        }
                    });
                }
            }
            //是否存在未删除的互斥商品 存在则不删除
            if(!mutexFlag.get()){
                promotionMerchantProductEntityMapper.update(updateParam);
            }
            //删除promotion_limit_rlue数据
            //3 商品SKU，4 优惠码 ,5 产品SPU
            Integer limitType = merchantProductEntity.getTypeOfProduct() == 10 ? 5 : 3;
            promotionLimitRuleEntityMapper.deleteByLimitTypeAndPidAndRef(merchantProductEntity.getPromotionId(), id, limitType);

        });
        return 1;
    }

    @Override
    public Integer deleteEntityByPromotionIdAndMpId(Long promotionId, Long mpId) {
        if(promotionId == null || mpId == null){
            return 0;
        }

        promotionMerchantProductEntityMapper.deleteEntityByPromotionIdAndMpId(promotionId, mpId);
        return 1;
    }

    @Override
    public PromotionMerchantProductEntity queryEntityByPromotionIdAndMpId(Long promotionId, Long mpId) {
        return promotionMerchantProductEntityMapper.queryEntityByPromotionIdAndMpId(promotionId, mpId);
    }

    @Override
    public Integer updateEntityByPromotionIdAndMpId(BigDecimal promPrice, Long promotionId, Long mpId) {
        promotionMerchantProductEntityMapper.updateEntityByPromotionIdAndMpId(promPrice, promotionId, mpId);
        return null;
    }

    @Override
    public void deleteProductBatch(List<Long> mpIds) {
        mpIds.forEach(x->{
            PromotionMerchantProductEntity productEntity = new PromotionMerchantProductEntity();
            productEntity.setDeleteFlag(1);
            productEntity.setId(x);
            promotionMerchantProductEntityMapper.update(productEntity);
        });
    }

    @Override
    public Integer updateCondition(Long promotionId, Long mpId, Integer mutexFlag, Date updateTime) {
        return promotionMerchantProductEntityMapper.updateCondition(promotionId, mpId, mutexFlag, updateTime);
    }

    @Override
    public Integer updateEntity(PromotionMerchantProductEntity pmpEntity) {
        return promotionMerchantProductEntityMapper.update(pmpEntity);
    }

    @Override
    public Integer saveBatch(List<PromotionProductRequest> productList) {
        log.info("============saveBatch-productList={}",productList);
        if (null == productList || productList.isEmpty()) {
            return 0;
        }
//        LoginUser currentLoginUser = loginService.getCurrentLoginUser();

        for (int i = 0; i < productList.size(); i++) {
            PromotionProductRequest temp = productList.get(i);
            log.info("============temp={}",temp);
            PromotionMerchantProductEntity dbEntity = promotionMerchantProductEntityMapper.queryEntityByPromotionIdAndMpId(temp.getPromotionId(), temp.getMpId());
            if(dbEntity!=null){
                continue;
            }
            PromotionMerchantProductEntity p = new PromotionMerchantProductEntity();
            p.setPromotionId(temp.getPromotionId());
//            p.setMerchantId(temp.getMerchantId());
//            p.setMpName(temp.getMpName());
//            p.setMpCode(temp.getMpCode());
//            p.setMerchantName(temp.getMerchantName());
//            p.setCreateTime(new Date());
//            p.setMpId(temp.getMpId());
//            p.setCategoryId(temp.getCategoryId());
//            p.setPicUrl(temp.getPicUrl());
//            p.setMpParentId(temp.getMpParentId());
//            p.setStoreName(temp.getStoreName());
//            p.setSalePriceWithTax(temp.getSalePriceWithTax());

//            p.setCreator(currentLoginUser.getId());
//            p.setCreatorName(currentLoginUser.getUsername());
//            p.setUpdateTime(new Date());
//            p.setUpdator(currentLoginUser.getId());
//            p.setUpdatorName(currentLoginUser.getUsername());


            int ret = promotionMerchantProductEntityMapper.insert(p);
            log.info("============saveBatch-after");
            if (ret < 1) {
                return 0;
            }
        }

        return 1;

    }

    @Override
    public List<PromotionMerchantProductEntity> saveBatchV2(List<PromotionMerchantProductEntity> productList) {
        log.info("============saveBatchV2-productList={}",productList);
        if (null == productList || productList.isEmpty()) {
            return null;
        }
        List<PromotionMerchantProductEntity> entityListNew =new ArrayList<>();
        for (PromotionMerchantProductEntity entity : productList) {
            promotionMerchantProductEntityMapper.insert(entity);
            entityListNew.add(entity);
        }
        log.info("============saveBatchV2-after");
        return entityListNew;
    }

    @Override
    public List<PromotionMerchantProductEntity> findOfPage(PromotionMerchantProductEntity productCondition, Pagination pagination) {
        return promotionMerchantProductEntityMapper.findOfPage(productCondition,pagination);
    }

    @Override
    public Integer countOfPage(PromotionMerchantProductEntity productCondition) {
        return promotionMerchantProductEntityMapper.countOfPage(productCondition);
    }

    private String getMerchanName(Long merchantId){
        List<Long> merchantList = new ArrayList<>();
        merchantList.add(merchantId);
        RestResult<List<MerchantRequest>> resultList = managerMerchantApi.queryMerchantListByid(merchantList);
        if(null != resultList && null != resultList.getData() && !resultList.getData().isEmpty()){
            return resultList.getData().get(0).getName();
        }
        return null;
    }

    private String getStoreName(Long storeId){
        RestResult<MemStoreResponse> result = managerStoreApi.getStoreInfo(storeId);
        if(null != result && null != result.getData()){
            return result.getData().getStoreName();
        }
        return null;
    }
//    private String getStoreName(Long storeId){
//        Mestore result = managerStoreApi.queryByPrimaryKey(storeId);
//        if(null != result){
//            return result.getStoreName();
//        }
//        return null;
//    }
    /**
     * 根据spu批量新增商品
     * @param request
     * @return
     */
    @Override
    @Transactional
    public Integer saveBatchV3(PromotionProductSaveBatchListRequest request) {
        List<PromotionProductSaveBatchRequest> batchSpuRequestList = request.getProductPromotionList();
        if(CollectionUtils.isEmpty(batchSpuRequestList)){
            return null;
        }
        final Long promotionId = batchSpuRequestList.get(0).getPromotionId();
        final List<PromotionMerchantProductEntity> productEntities = new ArrayList<>();
        final List<PromotionMerchantProductEntity> updateProductEntities = new ArrayList<>();

        List<Long> spuIds = batchSpuRequestList.stream().map(PromotionProductSaveBatchRequest::getSpuId).collect(Collectors.toList());
        GoodsPageQueryRequest goodsSkuQueryRequest = new GoodsPageQueryRequest();
        goodsSkuQueryRequest.setSpuIds(spuIds);

        List<ProductStoreInfo> goodsInfoResponseList = productListApi.queryProductBySpuId(goodsSkuQueryRequest);
//        RestResult<List<QueryGoodsInfoResponse>> listRestResult = goodsQueryService.queryByGoodsSpuIds(goodsSkuQueryRequest);
//        List<QueryGoodsInfoResponse> goodsInfoResponseList = listRestResult.getData();
        if(CollectionUtils.isEmpty(goodsInfoResponseList)){
            return null;
        }
        //获取互斥结果
        final MutexResultContext mutexResultContext = getMutexResultContext(promotionId, goodsInfoResponseList);
        final Set<Long> mutexList = mutexResultContext.getMutexList();
        //final Set<Long> noMutexList = mutexResultContext.getNoMutexList();
        final Map<Long, Set<MutexProductEntity>> mutexPromotionProducts = mutexResultContext.getMutexPromotionProducts();
        final Map<Long, Long> mutexMpIdMap = Maps.newHashMap();


        goodsInfoResponseList.forEach(goodsInfo->{
            ProductStoreInfo goodsSpuInfo = goodsInfo;
            List<ProductStoreInfo> goodsSkuInfoList = goodsInfo.getChildren();
            //SPU
            PromotionMerchantProductEntity spuParam = new PromotionMerchantProductEntity();
            spuParam.setMpId(goodsSpuInfo.getId());
            spuParam.setPromotionId(promotionId);
            spuParam.setTypeOfProduct(TypeOfProductEnum.GOODS_SPU.getCode());
            List<PromotionMerchantProductEntity> spuList = promotionMerchantProductEntityMapper.findAll(spuParam);
            if(CollectionUtils.isNotEmpty(spuList)){
                spuList.forEach(s->{
                    if(s.getDeleteFlag() == 1){
                        PromotionMerchantProductEntity updateParam = new PromotionMerchantProductEntity();
                        updateParam.setId(s.getId());
                        updateParam.setDeleteFlag(0);
                        updateParam.setMutexFlag(mutexList.contains(goodsSpuInfo.getId()) ? MutexFlagEnum.MUTEX.getCode() : MutexFlagEnum.UN_MUTEX.getCode());
                        updateParam.setMerchantName(getMerchanName(s.getMerchantId()));
                        updateParam.setStoreName(getStoreName(s.getStoreId()));
                        promotionMerchantProductEntityMapper.update(updateParam);
                    }
                    if(mutexList.contains(goodsSpuInfo.getId())){
                        mutexMpIdMap.put(goodsSpuInfo.getId(), s.getId());
                    }
                });
            }else{
                //组装entity
                PromotionMerchantProductEntity spuEntity = new PromotionMerchantProductEntity();
                spuEntity.setMpId(goodsSpuInfo.getId());
                spuEntity.setPromotionId(promotionId);
                spuEntity.setMpName(goodsSpuInfo.getChineseName());
                spuEntity.setMpParentId(0L);
                spuEntity.setTypeOfProduct(TypeOfProductEnum.GOODS_SPU.getCode());
                spuEntity.setCategoryName(goodsSpuInfo.getCategoryName());
                spuEntity.setScopeType(ProductScopeTypeEnum.PRODUCT.getCode());
                spuEntity.setMutexFlag(mutexList.contains(goodsSpuInfo.getId()) ? MutexFlagEnum.MUTEX.getCode() : MutexFlagEnum.UN_MUTEX.getCode());
                spuEntity.setStatus(0);
                spuEntity.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
                spuEntity.setStoreId(goodsSpuInfo.getStoreId());
                spuEntity.setMerchantId(goodsSpuInfo.getMerchantId());
                spuEntity.setCreator(request.getCreator());
                spuEntity.setUpdator(request.getUpdator());
                spuEntity.setCreateTime(new Date());
                spuEntity.setUpdatorName(request.getUpdatorName());
                spuEntity.setUpdateTime(new Date());
                spuEntity.setMpCode(goodsSpuInfo.getCode());
                spuEntity.setMerchantName(getMerchanName(goodsSpuInfo.getMerchantId()));
                spuEntity.setStoreName(getStoreName(goodsSpuInfo.getStoreId()));
//                spuEntity.setAlreadyFrontCount(0);
//                spuEntity.setFrontMoney(new BigDecimal(0));
//                spuEntity.setFrontMoneyDeductAmount(new BigDecimal(0));
//                spuEntity.setChannelMerchantLimit(0);
//                spuEntity.setChannelStoreLimit(0);
//                spuEntity.setChannelIndividualLimit(0);
                productEntities.add(spuEntity);
            }

            //SKU
            if(CollectionUtils.isNotEmpty(goodsSkuInfoList)){
                goodsSkuInfoList.forEach(goodsSkuInfo -> {
                    PromotionMerchantProductEntity skuParam = new PromotionMerchantProductEntity();
                    skuParam.setMpId(goodsSkuInfo.getId());
                    skuParam.setPromotionId(promotionId);
                    skuParam.setTypeOfProduct(TypeOfProductEnum.GOODS_SKU.getCode());
                    List<PromotionMerchantProductEntity> skuList = promotionMerchantProductEntityMapper.findAll(skuParam);
                    if(CollectionUtils.isNotEmpty(skuList)){
                        skuList.forEach(sk->{
                            if(sk.getDeleteFlag() == 1){
                                PromotionMerchantProductEntity updateParam = new PromotionMerchantProductEntity();
                                updateParam.setId(sk.getId());
                                updateParam.setDeleteFlag(0);
                                updateParam.setMutexFlag(mutexList.contains(goodsSkuInfo.getId()) ? MutexFlagEnum.MUTEX.getCode() : MutexFlagEnum.UN_MUTEX.getCode());
                                updateParam.setMerchantName(getMerchanName(sk.getMerchantId()));
                                updateParam.setStoreName(getStoreName(sk.getStoreId()));
                                updateParam.setAlreadyFrontCount(0l);
                                updateParam.setFrontMoney(new BigDecimal(0));
                                updateParam.setFrontMoneyDeductAmount(new BigDecimal(0));
                                updateParam.setChannelMerchantLimit(0l);
                                updateParam.setChannelStoreLimit(0l);
                                updateParam.setChannelIndividualLimit(0l);
                                promotionMerchantProductEntityMapper.updateCanNull(updateParam);
                            }
                            if(mutexList.contains(goodsSkuInfo.getId())){
                                mutexMpIdMap.put(goodsSkuInfo.getId(), sk.getId());
                            }
                        });
                    }else{
                        //组装entity
                        PromotionMerchantProductEntity entity = new PromotionMerchantProductEntity();
                        entity.setMpId(goodsSkuInfo.getId());
                        entity.setPromotionId(promotionId);
                        entity.setMpName(goodsSkuInfo.getChineseName());
                        entity.setTypeOfProduct(TypeOfProductEnum.GOODS_SKU.getCode());
                        entity.setMpParentId(goodsSpuInfo.getId());
                        entity.setCategoryName(goodsSkuInfo.getCategoryName());
                        entity.setMerchantId(goodsSkuInfo.getMerchantId());
                        entity.setScopeType(ProductScopeTypeEnum.PRODUCT.getCode());
                        entity.setStoreId(goodsSkuInfo.getStoreId());
                        entity.setMutexFlag(mutexList.contains(goodsSkuInfo.getId()) ? MutexFlagEnum.MUTEX.getCode() : MutexFlagEnum.UN_MUTEX.getCode());
                        entity.setStatus(0);
                        entity.setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
                        entity.setCreator(request.getCreator());
                        entity.setUpdator(request.getUpdator());
                        entity.setCreateTime(new Date());
                        entity.setUpdatorName(request.getUpdatorName());
                        entity.setUpdateTime(new Date());
                        entity.setMpCode(goodsSkuInfo.getCode());
                        entity.setMerchantName(getMerchanName(goodsSkuInfo.getMerchantId()));
                        entity.setStoreName(getStoreName(goodsSkuInfo.getStoreId()));
                        entity.setAlreadyFrontCount(0L);
                        entity.setFrontMoney(new BigDecimal(0));
                        entity.setFrontMoneyDeductAmount(new BigDecimal(0));
                        entity.setChannelMerchantLimit(0L);
                        entity.setChannelStoreLimit(0L);
                        entity.setChannelIndividualLimit(0L);
                        productEntities.add(entity);
                    }
                });
            }
        });

        if(CollectionUtils.isNotEmpty(productEntities)){
            promotionMerchantProductEntityMapper.insertBatchNew(productEntities);
        }
        productEntities.forEach(x->{
            if(mutexList.contains(x.getMpId())){
                mutexMpIdMap.put(x.getMpId(), x.getId());
            }
        });
        //插入互斥表
        mutexPromotionProducts.entrySet().forEach(e->{
            Set<MutexProductEntity> mutexProductEntitySet = e.getValue();
            promotionMutexService.deleteByPromotionProductId(mutexMpIdMap.get(e.getKey()));
            List<PromotionMutex> collect = mutexProductEntitySet.stream().map(m -> {
                return new PromotionMutex()
                        .setPromotionId(m.getPromotionId())
                        .setPromType(m.getPromType())
                        .setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode())
                        .setPromotionMerchantProductId(mutexMpIdMap.get(e.getKey()))
                        .setCreator(request.getCreator())
                        .setCreatorName(request.getCreatorName())
                        .setUpdator(request.getUpdator())
                        .setCreateTime(new Date())
                        .setUpdatorName(request.getUpdatorName());
            }).collect(Collectors.toList());
            promotionMutexService.insertBatch(collect);
//            mutexProductEntitySet.forEach(m->{
//                promotionMutexService.insert(
//                        new PromotionMutex()
//                        .setPromotionId(m.getPromotionId())
//                        .setPromType(m.getPromType())
//                        .setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode())
//                        .setPromotionMerchantProductId(mutexMpIdMap.get(e.getKey()))
//                        .setCreator(request.getCreator())
//                        .setCreatorName(request.getCreatorName())
//                        .setUpdator(request.getUpdator())
//                        .setUpdatorName(request.getUpdatorName())
//                );
//            });
        });

        return productEntities.size();
    }

    /**
     * 获取互斥结果
     * @param promotionId
     * @param goodsInfoResponseList
     * @return
     */
    private MutexResultContext getMutexResultContext(Long promotionId, List<ProductStoreInfo> goodsInfoResponseList) {
        final List<Long> productList = Lists.newArrayList();
        goodsInfoResponseList.forEach(spu->{
            //productList.add(spu.getGoodsSpuInfo().getId());
            List<ProductStoreInfo> goodsSkuInfoList = spu.getChildren();
            goodsSkuInfoList.forEach(sku->{
                productList.add(sku.getId());
            });
        });
        PromotionEntity promotionEntity = promotionEntityMapper.queryById(promotionId);
        if(promotionEntity.getPromType().equals(PromotionTypeEnum.PAYMENT_REDUCTION.getCode())){
            List<String> payFrontPromotionTypeList = Arrays.asList(promotionEntity.getPayFrontPromType().split(","));
            return mutexService.doProcessMutexByPayment(
                    new MutexModel()
                            .setPromotionId(promotionId)
                            .setPromType(promotionEntity.getPromType())
                            .setPayFrontPromotionTypeList(payFrontPromotionTypeList)
                            .setProductList(productList)
            );
        }else{

            return mutexService.doProcessMutex(
                    new MutexModel()
                            .setPromotionId(promotionId)
                            .setPromType(promotionEntity.getPromType())
                            .setFrontPromotionType(promotionEntity.getFrontPromType())
                            .setProductList(productList)
            );
        }
    }

    @Override
    public PageResponse<PromotionProductResponse> getProductList(PromotionMerchantProductRequest request) {
        final Long promotionId = request.getPromotionId();
        PromotionMerchantProductEntity spuParam = new PromotionMerchantProductEntity();
        Pagination pagination = Pagination.build(request.getStart(), request.getLimit());
        spuParam.setPromotionId(promotionId);
        spuParam.setDeleteFlag(0);
        spuParam.setTypeOfProduct(TypeOfProductEnum.GOODS_SPU.getCode());
        spuParam.setMpName(request.getMpName());
        spuParam.setMpCode(request.getMpCode());
        spuParam.setCategoryName(request.getCategoryName());
        spuParam.setMerchantId(request.getMerchantId());
        spuParam.setMutexFlag(request.getMutexFlag());
        spuParam.setStoreId(request.getStoreId());
        List<PromotionMerchantProductEntity> ofPage = promotionMerchantProductEntityMapper.findMutexOfPageV2(spuParam, pagination);

        List<PromotionProductResponse> responseList = ofPage.stream().map(x -> {
            PromotionProductResponse response = new PromotionProductResponse();
            PromotionLimitRuleEntity spuLimitRule = new PromotionLimitRuleEntity();
            spuLimitRule.setLimitType(PromotionLimitRuleLimitTypeEnum.SPU_TYPE.getCode());
            spuLimitRule.setLimitRef(x.getMpId());
            spuLimitRule.setPromotionId(promotionId);
            spuLimitRule.setDeleteFlag(0);
            //PromotionLimitRuleEntity entityByPromotionIdAndMpId = promotionLimitRuleEntityMapper.getEntityByPromotionIdAndMpId(promotionId, x.getMpId());
            List<PromotionLimitRuleEntity> spuLimits = promotionLimitRuleEntityMapper.findAll(spuLimitRule);
            //查询 promotion_single_rule
            PromotionSingleRuleEntity promotionSingleSpu = new PromotionSingleRuleEntity(){{
                setPromotionId(promotionId);
                setProductId(x.getMpId());
                setTypeOfProduct(1);
            }};
            PromotionSingleRuleEntity promotionSingleValueSpu = promotionSingleRuleEntityMapper.queryEntityByPromotionIdAndMpId(promotionSingleSpu);
            BeanUtils.copyProperties(x, response);
            response.setStoreName(getStoreName(x.getStoreId()));
            response.setChannelIndividualLimit(null);
            response.setChannelMerchantLimit(null);
            response.setChannelStoreLimit(null);
            //获取售价和库存
//            GoodsSpu goodsSpu = goodsSpuMapper.queryByPrimaryKey(x.getMpId());
            List<ProductStoreInfo> productStoreInfos = productListApi.queryProductBySpuList(new GoodsPageQueryRequest() {{
                setId(x.getMpId());
            }});
            ProductStoreInfo goodsSpu = productStoreInfos.get(0);
            response.setStock(goodsSpu != null ? goodsSpu.getAvailableStock().intValue() : null);
            response.setSalePrice(goodsSpu != null ? goodsSpu.getSalePriceWithTax().toString() : null);
            if(CollectionUtils.isNotEmpty(spuLimits)){
                response.setPlatformTotalLimit(spuLimits.get(0).getPlatformTotalLimit());
                response.setChannelMerchantLimit(spuLimits.get(0).getChannelMerchantLimit());
                response.setChannelStoreLimit(spuLimits.get(0).getChannelStoreLimit());
                response.setChannelIndividualLimit(spuLimits.get(0).getChannelIndividualLimit());
                response.setTotalLimit(spuLimits.get(0).getTotalLimit());
                response.setIndividualLimit(spuLimits.get(0).getIndividualLimit());
                response.setTotalLimitAmount(spuLimits.get(0).getTotalLimitAmount());
                response.setOrderLimit(spuLimits.get(0).getOrderLimit());
                response.setLimitRuleId(spuLimits.get(0).getId());
                response.setStockLimit(spuLimits.get(0).getStockLimit());
                response.setParentAllocationScale(spuLimits.get(0).getParentAllocationScale());
                response.setMerchantAllocationScale(spuLimits.get(0).getMerchantAllocationScale());
            }
            //特价、折扣、直降
            if (promotionSingleValueSpu !=null){
                response.setContentValue(promotionSingleValueSpu.getContentValue());
            }

            //获取SKU
            List<PromotionProductSonResponse> children = null;
            PromotionMerchantProductEntity skuParam = new PromotionMerchantProductEntity();
            skuParam.setPromotionId(promotionId);
            skuParam.setDeleteFlag(0);
            skuParam.setMpParentId(x.getMpId());
            skuParam.setTypeOfProduct(TypeOfProductEnum.GOODS_SKU.getCode());
            skuParam.setMutexFlag(request.getMutexFlag());
            List<PromotionMerchantProductEntity> allSku = promotionMerchantProductEntityMapper.findAll(skuParam);
            if(CollectionUtils.isNotEmpty(allSku)){
                children = allSku.stream().map(sku->{
                    PromotionProductSonResponse skuResponse = new PromotionProductSonResponse();
                    BeanUtils.copyProperties(sku, skuResponse);
                    skuResponse.setStoreName(getStoreName(sku.getStoreId()));
                    //限制条件查询请在promotion_limit_rule
                    skuResponse.setChannelIndividualLimit(null);
                    skuResponse.setChannelMerchantLimit(null);
                    skuResponse.setChannelStoreLimit(null);
                    //售价&库存
//                    GoodsSku goodsSku = goodsSkuMapper.queryByPrimaryKey(sku.getMpId());
                    List<ProductStoreInfo> skuList = productListApi.queryProductBySpuList(new GoodsPageQueryRequest() {{
                        setId(sku.getMpId());
                    }});

                    ProductStoreInfo goodsSku = skuList.get(0);

                    skuResponse.setStock(goodsSku != null ? goodsSku.getAvailableStock().intValue() : null);
                    skuResponse.setSalePrice(goodsSku != null ? goodsSku.getSalePriceWithTax().toString() : null);

                    PromotionLimitRuleEntity skuLimitRule = new PromotionLimitRuleEntity();
                    skuLimitRule.setLimitType(PromotionLimitRuleLimitTypeEnum.SKU_TYPE.getCode());
                    skuLimitRule.setLimitRef(sku.getMpId());
                    skuLimitRule.setPromotionId(promotionId);
                    skuLimitRule.setDeleteFlag(0);
//                    PromotionLimitRuleEntity skuLimitRule = promotionLimitRuleEntityMapper.getEntityByPromotionIdAndMpId(promotionId, sku.getMpId());
                    List<PromotionLimitRuleEntity> skuLimits = promotionLimitRuleEntityMapper.findAll(skuLimitRule);
                    //查询 promotion_single_rule
                    PromotionSingleRuleEntity promotionSingleSku = new PromotionSingleRuleEntity(){{
                        setPromotionId(promotionId);
                        setProductId(sku.getMpId());
                        setTypeOfProduct(2);
                    }};
                    PromotionSingleRuleEntity promotionSingleValueSku = promotionSingleRuleEntityMapper.queryEntityByPromotionIdAndMpId(promotionSingleSku);

                    if(CollectionUtils.isNotEmpty(skuLimits)){
                       skuResponse.setPlatformTotalLimit(skuLimits.get(0).getPlatformTotalLimit());
                       skuResponse.setChannelMerchantLimit(skuLimits.get(0).getChannelMerchantLimit());
                       skuResponse.setChannelStoreLimit(skuLimits.get(0).getChannelStoreLimit());
                       skuResponse.setChannelIndividualLimit(skuLimits.get(0).getChannelIndividualLimit());
                       skuResponse.setTotalLimit(skuLimits.get(0).getTotalLimit());
                       skuResponse.setIndividualLimit(skuLimits.get(0).getIndividualLimit());
                       skuResponse.setTotalLimitAmount(skuLimits.get(0).getTotalLimitAmount());
                       skuResponse.setOrderLimit(skuLimits.get(0).getOrderLimit());
                       skuResponse.setLimitRuleId(skuLimits.get(0).getId());
                       skuResponse.setStockLimit(skuLimits.get(0).getStockLimit());
                       skuResponse.setParentAllocationScale(skuLimits.get(0).getParentAllocationScale());
                       skuResponse.setMerchantAllocationScale(skuLimits.get(0).getMerchantAllocationScale());
                    }
                    //特价、折扣、直降
                    if (promotionSingleValueSku !=null){
                        skuResponse.setContentValue(promotionSingleValueSku.getContentValue());
                    }
                    return skuResponse;
                }).collect(Collectors.toList());
            }
            response.setChildren(children);
            return response;
        }).collect(Collectors.toList());

        int count = promotionMerchantProductEntityMapper.countMutexOfPageV2(spuParam);
        PromotionMerchantProductEntity countParam = new PromotionMerchantProductEntity();
        countParam.setPromotionId(promotionId);
        countParam.setDeleteFlag(0);
        countParam.setTypeOfProduct(TypeOfProductEnum.GOODS_SKU.getCode());
        countParam.setMutexFlag(request.getMutexFlag());
        countParam.setMpName(request.getMpName());
        countParam.setMpCode(request.getMpCode());
        countParam.setCategoryName(request.getCategoryName());
        countParam.setMerchantId(request.getMerchantId());
        int totalCount = promotionMerchantProductEntityMapper.countOfPage(countParam);
        PageResponse<PromotionProductResponse> pageResult = new PageResponse<PromotionProductResponse>()
                .setTotal(count)
                .setTotalCount(totalCount)
                .setRows(responseList);
        return pageResult;
    }


    @Override
    public Integer deleteProductV2(Long id) {
        //根据id获取
        PromotionMerchantProductEntity merchantProductEntity = promotionMerchantProductEntityMapper.queryEntityById(id);
        if(merchantProductEntity == null || merchantProductEntity.getDeleteFlag() == 1){
            return 0;
        }

        PromotionMerchantProductEntity updateParam = new PromotionMerchantProductEntity();
        updateParam.setId(id);
        updateParam.setDeleteFlag(1);
        updateParam.setChannelMerchantLimit(0l);
        updateParam.setChannelStoreLimit(0l);
        updateParam.setChannelIndividualLimit(0l);
        //是否存在未删除的互斥商品
        AtomicBoolean mutexFlag = new AtomicBoolean(false);
        //删除所有sku
        if(merchantProductEntity.getTypeOfProduct() == 10) {
            PromotionMerchantProductEntity productEntity = new PromotionMerchantProductEntity();
            productEntity.setMpParentId(merchantProductEntity.getMpId());
            productEntity.setDeleteFlag(0);
            productEntity.setPromotionId(merchantProductEntity.getPromotionId());
            List<PromotionMerchantProductEntity> all = promotionMerchantProductEntityMapper.findAll(productEntity);
            if (CollectionUtils.isNotEmpty(all)) {
                all.stream().forEach(x -> {
                    if(MutexFlagEnum.MUTEX.getCode().equals(x.getMutexFlag())&& DeleteFlagEnum.UN_DELETE.getCode().equals(x.getDeleteFlag())){
                        mutexFlag.set(true);
                    }else {
                        deleteProductV2(x.getId());
                    }
                });
            }
        }else if(merchantProductEntity.getTypeOfProduct() == 20) {
            // 如果删除的是sku，则判断sku有没有剩余的，如果没有，则自动删除spu
            PromotionMerchantProductEntity productEntity = new PromotionMerchantProductEntity();
            productEntity.setMpParentId(merchantProductEntity.getMpParentId());
            productEntity.setDeleteFlag(0);
            productEntity.setPromotionId(merchantProductEntity.getPromotionId());
            List<PromotionMerchantProductEntity> all = promotionMerchantProductEntityMapper.findAll(productEntity);
            if (CollectionUtils.isEmpty(all)) {
                promotionMerchantProductEntityMapper.deleteEntityByPromotionIdAndMpId(merchantProductEntity.getPromotionId(),merchantProductEntity.getMpParentId());
                promotionLimitRuleEntityMapper.deleteByLimitTypeAndPidAndRef(merchantProductEntity.getPromotionId(), merchantProductEntity.getMpParentId(), 5);
            }
        }
        //是否存在未删除的互斥商品 存在则不删除
        if(!mutexFlag.get()){
            promotionMerchantProductEntityMapper.update(updateParam);
        }
            //删除promotion_limit_rlue数据
        //3 商品SKU，4 优惠码 ,5 产品SPU
        Integer limitType = merchantProductEntity.getTypeOfProduct() == 10 ? 5 : 3;
        promotionLimitRuleEntityMapper.deleteByLimitTypeAndPidAndRef(merchantProductEntity.getPromotionId(), merchantProductEntity.getMpId(), limitType);

        //删除promotion_single_rule
        Integer productType = merchantProductEntity.getTypeOfProduct() == 10 ? 1 : 2;
        promotionSingleRuleEntityMapper.deleteByLimitTypeAndPidAndRef(merchantProductEntity.getPromotionId(), merchantProductEntity.getMpId(), productType);
        return 1;
    }


    @Override
    public Integer deleteProductV3(Long id) {
        //根据id获取
        PromotionMerchantProductEntity merchantProductEntity = promotionMerchantProductEntityMapper.queryEntityById(id);
        if(merchantProductEntity == null || merchantProductEntity.getDeleteFlag() == 1){
            return 0;
        }

        PromotionMerchantProductEntity updateParam = new PromotionMerchantProductEntity();
        updateParam.setId(id);
        updateParam.setDeleteFlag(1);
        updateParam.setChannelMerchantLimit(0l);
        updateParam.setChannelStoreLimit(0l);
        updateParam.setChannelIndividualLimit(0l);
        promotionMerchantProductEntityMapper.update(updateParam);
        //删除所有sku
        if(merchantProductEntity.getTypeOfProduct() == 10) {
            PromotionMerchantProductEntity productEntity = new PromotionMerchantProductEntity();
            productEntity.setMpParentId(merchantProductEntity.getMpId());
            productEntity.setDeleteFlag(0);
            productEntity.setPromotionId(merchantProductEntity.getPromotionId());
            List<PromotionMerchantProductEntity> all = promotionMerchantProductEntityMapper.findAll(productEntity);
            if (CollectionUtils.isNotEmpty(all)) {
                all.stream().forEach(x -> {
                   deleteProductV3(x.getId());
                });
            }
        }else if(merchantProductEntity.getTypeOfProduct() == 20) {
            // 如果删除的是sku，则判断sku有没有剩余的，如果没有，则自动删除spu
            PromotionMerchantProductEntity productEntity = new PromotionMerchantProductEntity();
            productEntity.setMpParentId(merchantProductEntity.getMpParentId());
            productEntity.setDeleteFlag(0);
            productEntity.setPromotionId(merchantProductEntity.getPromotionId());
            List<PromotionMerchantProductEntity> all = promotionMerchantProductEntityMapper.findAll(productEntity);
            if (CollectionUtils.isEmpty(all)) {
                promotionMerchantProductEntityMapper.deleteEntityByPromotionIdAndMpId(merchantProductEntity.getPromotionId(),merchantProductEntity.getMpParentId());
                promotionLimitRuleEntityMapper.deleteByLimitTypeAndPidAndRef(merchantProductEntity.getPromotionId(), merchantProductEntity.getMpParentId(), 5);
            }
        }
        //删除promotion_limit_rlue数据
        //3 商品SKU，4 优惠码 ,5 产品SPU
        Integer limitType = merchantProductEntity.getTypeOfProduct() == 10 ? 5 : 3;
        promotionLimitRuleEntityMapper.deleteByLimitTypeAndPidAndRef(merchantProductEntity.getPromotionId(), merchantProductEntity.getMpId(), limitType);

        //删除promotion_single_rule
        Integer productType = merchantProductEntity.getTypeOfProduct() == 10 ? 1 : 2;
        promotionSingleRuleEntityMapper.deleteByLimitTypeAndPidAndRef(merchantProductEntity.getPromotionId(), merchantProductEntity.getMpId(), productType);
        return 1;
    }

    @Override
    public Integer addAllProduct(PromotinAddAllProductRequest request) {
        PromotionProductSaveBatchListRequest productSaveBatchListRequest = new PromotionProductSaveBatchListRequest();
        final Long promotionId = request.getPromotionId();
        GoodsPageQueryRequest goodsPageQueryRequest =new GoodsPageQueryRequest();
        goodsPageQueryRequest.setStoreIds(getStoreIdsByPromotionId(promotionId));
       // goodsPageQueryRequest.setMerchantIds(request.getMerchantId());
        goodsPageQueryRequest.setId(request.getSpuId());
        goodsPageQueryRequest.setGoodsCategory(request.getGoodsCategory());
        goodsPageQueryRequest.setGoodsName(request.getGoodsName());

        List<ProductStoreInfo> list = productListApi.queryProductBySpuList(goodsPageQueryRequest);
//        goodsPageQueryRequest.setChildIds(request.getChildIds());
//        RestResult<List<GoodsPageQueryResponse>> listRestResult = goodsQueryService.queryByAllCondition(goodsPageQueryRequest);

//        List<GoodsPageQueryResponse> list = listRestResult.getData();
        if(CollectionUtils.isEmpty(list)){
            return 0;
        }
        List<PromotionProductSaveBatchRequest> collect = list.stream().map(x -> {
            PromotionProductSaveBatchRequest productSaveBatchRequest = new PromotionProductSaveBatchRequest();
            productSaveBatchRequest.setSpuId(x.getId());
            productSaveBatchRequest.setPromotionId(promotionId);
            return productSaveBatchRequest;
        }).collect(Collectors.toList());
        productSaveBatchListRequest.setProductPromotionList(collect);
        return this.saveBatchV3(productSaveBatchListRequest);
    }

    private List<Long> getStoreIdsByPromotionId(Long id){
        //默认值
        List<Long> storeIds = Arrays.asList(-99L);
        if(id == null){
            return storeIds;
        }
        PromotionMerchantEntity promotionMerchantEntity = new PromotionMerchantEntity();
        promotionMerchantEntity.setPromotionId(id);
        promotionMerchantEntity.setMerchantType(2);
        promotionMerchantEntity.setDeleteFlag(0);
        List<PromotionMerchantEntity> all = promotionMerchantEntityMapper.findAll(promotionMerchantEntity);
        if(!com.alibaba.excel.util.CollectionUtils.isEmpty(all)){
            storeIds = all.stream().map(PromotionMerchantEntity::getStoreId).collect(Collectors.toList());
        }
        return storeIds;
    }

    @Override
    public void deletProductByStoreIdsAndPromotionId(List<Long> storeIds, Long promotionId) {
        PromotionMerchantProductEntity productEntity = new PromotionMerchantProductEntity();
        productEntity.setPromotionId(promotionId);
        productEntity.setStoreIds(storeIds);
        productEntity.setDeleteFlag(0);
        List<PromotionMerchantProductEntity> all = promotionMerchantProductEntityMapper.findAll(productEntity);
        all.forEach(x->{
            deleteProductV3(x.getId());
        });
    }

    @Override
    public Long skuCount(PromotionProductSkuCountRequest request) {
        return promotionMerchantProductEntityMapper.skuCount(request.getPromotionId());
    }

    @Override
    public void updatePresellInfo(PromotionUpdatePresellInfoRequest request) {
        PromotionMerchantProductEntity promotionMerchantProductEntity = new PromotionMerchantProductEntity();
        BeanUtils.copyProperties(request, promotionMerchantProductEntity);
        promotionMerchantProductEntityMapper.update(promotionMerchantProductEntity);
    }

    @Override
    public RestResult<Map<String,Object>> renewAddMutexProduct(RenewAddMutexProductRequest renewAddMutexProductRequest) {
        Map<String,Object> restMap = new HashMap<String, Object>();
        Integer generalType = 1;
        Integer groupType = 2;

        try{
            //查询需要重新添加的商品数据
            Integer promotionType = renewAddMutexProductRequest.getPromotionType();
            List<Long> productEntityIdList = new ArrayList<>();
            PromotionEntity promotionEntity = new PromotionEntity();
            if(generalType.equals(promotionType)){
                //查询通用
                productEntityIdList =  promotionMerchantProductEntityMapper.queryEntityListByIds(StringUtils.join(renewAddMutexProductRequest.getProductIdList(),","));
                promotionEntity = promotionEntityMapper.queryById(renewAddMutexProductRequest.getPromotionId());
            }else if(groupType.equals(promotionType)){
                //查询拼团
                promotionEntity.setPromType(PromotionTypeEnum.GROUPON.getCode());
                promotionEntity.setFrontPromType(FrontPromotionTypeEnum.GROUPON.getCode());
                productEntityIdList = patchGrouponMpEntityMapper.queryEntityListByIds(StringUtils.join(renewAddMutexProductRequest.getProductIdList(),","));
            }else{
                return RestResult.error("9999","未知的活动类型");
            }
            MutexModel mutexModel = new MutexModel();
            mutexModel.setPromotionId(renewAddMutexProductRequest.getPromotionId());
            mutexModel.setProductList(productEntityIdList);
            mutexModel.setPromType( promotionEntity.getPromType());
            mutexModel.setFrontPromotionType( promotionEntity.getFrontPromType());

            MutexResultContext mutexResultContext = mutexService.doProcessMutex(mutexModel);
            Set<Long> mutexList = mutexResultContext.getMutexList();
            if (CollectionUtils.isEmpty(mutexList)){
                //如果互斥列表为空 证明不互斥 删除记录修改merchant_product的记录
                if(generalType.equals(promotionType)){
                    //更新通用
                    promotionMerchantProductEntityMapper.updateMutexByIds(StringUtils.join(renewAddMutexProductRequest.getProductIdList(),","));
                }else{
                    //拼团
                    patchGrouponMpEntityMapper.updateMutexByIds(StringUtils.join(renewAddMutexProductRequest.getProductIdList(),","));
                }
                //删除互斥记录表
                promotionMutexMapper.deleteMutexByPromotionIdAndMerchantProductIds(renewAddMutexProductRequest.getPromotionId(),
                        StringUtils.join(renewAddMutexProductRequest.getProductIdList(),","),promotionEntity.getPromType());
                //重新添加成功
                restMap.put("businessCode", "0001");
                restMap.put("businessMsg", "商品添加成功");
            }else{
                //不为空 证明还存在互斥 更新互斥的商品和记录
                Set<Long> noMutexList = mutexResultContext.getNoMutexList();

                if (CollectionUtils.isNotEmpty(noMutexList)) {
                    if (generalType.equals(promotionType)){
                        promotionMerchantProductEntityMapper.updateNoMutexListByPromotionIdAndMpIdAndSkillTimeId(renewAddMutexProductRequest.getPromotionId(),
                                renewAddMutexProductRequest.getSkillTimeId(),StringUtils.join(noMutexList,","));
                    }else{
                        //更新拼团互斥
                        patchGrouponMpEntityMapper.updateNoMutexListByPromotionIdAndMpId(renewAddMutexProductRequest.getPromotionId(),StringUtils.join(noMutexList,","));
                    }
                }else{
                    restMap.put("businessCode", "0002");
                    restMap.put("businessMsg", "互斥活动尚未结束，请在活动结束后操作");
                }

                List<String> restProduct = new ArrayList<>();

                //新增新的记录
                Map<Long, Set<MutexProductEntity>> mutexPromotionProducts = mutexResultContext.getMutexPromotionProducts();
                //商品id 活动
                for(Map.Entry<Long, Set<MutexProductEntity>> entry : mutexPromotionProducts.entrySet()){
                    Set<MutexProductEntity> mutexProductEntitySetList = entry.getValue();
                    mutexProductEntitySetList.stream().forEach(item->{
                        //删除记录
                        PromotionMutex promotionMutex = new PromotionMutex();
                        promotionMutex.setPromotionId(item.getPromotionId());
                        promotionMutex.setPromType(item.getPromType());
                        promotionMutex.setPromotionMerchantProductId(item.getPromotionMerchantProductId());
                        promotionMutexMapper.deleteListByPromotionIdAndPromType(promotionMutex);
                    });
                    if (generalType.equals(promotionType)){
                        //查询promotionId mp_id skill_time_id 查询merchantProudct表主键
                        PromotionMerchantProductEntity productEntity = promotionMerchantProductEntityMapper.query(new PromotionMerchantProductEntity() {{
                            setPromotionId(renewAddMutexProductRequest.getPromotionId());
                            setSkillTimeId(renewAddMutexProductRequest.getSkillTimeId());
                            setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
                            setMutexFlag(MutexFlagEnum.MUTEX.getCode());
                            setMpId(entry.getKey());
                        }});

                        if(productEntity == null){
                            continue;
                        }else{
                            restProduct.add(productEntity.getMpName());
                            Set<MutexProductEntity> mutexProductEntitySet = entry.getValue();
                            promotionMutexService.deleteByPromotionProductId(productEntity.getId());
                            mutexProductEntitySet.forEach(mutexProductEntity -> {
                                //查询活动信息
                                promotionMutexService.insert(new PromotionMutex(){{
                                    setPromotionMerchantProductId(productEntity.getId());
                                    setPromType(mutexProductEntity.getPromType());
                                    setPromotionId(mutexProductEntity.getPromotionId());
                                    setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
                                    setCreateTime(new Date());
                                }});
                            });
                        }
                    }else{
                        //拼团
                        PatchGrouponMpEntity patchGrouponMpEntity = patchGrouponMpEntityMapper.query(new PatchGrouponMpEntity() {{
                            setPromotionId(renewAddMutexProductRequest.getPromotionId());
                            setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
                            setMutexFlag(MutexFlagEnum.MUTEX.getCode());
                            setMpId(entry.getKey());
                        }});
                        if(patchGrouponMpEntity == null){
                            continue;
                        }else{
                            restProduct.add(patchGrouponMpEntity.getMpName());
                            Set<MutexProductEntity> mutexProductEntitySet = entry.getValue();
                            promotionMutexService.deleteByPromotionProductId(patchGrouponMpEntity.getId());
                            mutexProductEntitySet.forEach(mutexProductEntity -> {
                                //查询活动信息
                                promotionMutexService.insert(new PromotionMutex(){{
                                    setPromotionMerchantProductId(patchGrouponMpEntity.getId());
                                    setPromType(mutexProductEntity.getPromType());
                                    setPromotionId(mutexProductEntity.getPromotionId());
                                    setDeleteFlag(DeleteFlagEnum.UN_DELETE.getCode());
                                    setCreateTime(new Date());
                                }});
                            });
                        }
                    }
                }
                restMap.put("businessCode", "0003");
                restMap.put("businessMsg", StringUtils.join(restProduct,"、")+"商品存在互斥活动，请在活动结束后再进行添加");
            }
        }catch (Exception e){
            log.error("重新添加互斥商品错误======>>>>>>{}",e);
            return RestResult.error("9999","服务器异常，请重新尝试...");
        }
        return RestResult.success(restMap);
    }

    @Override
    public RestResult<PresellProductResponse> queryPresellByMpId(PresellProductRequest request) {
        PresellProductResponse response = promotionMerchantProductEntityMapper.queryPresellByMpId(request);

        return RestResult.success(response);
    }

    @Override
    public RestResult<PromotionPolymericResponse> queryPromotionProduct(PromotionPolymericRequest request) {
        if (StringUtils.isEmpty(request.getPromotionId()) || request.getPromotionType() == null){
            return RestResult.error("9999","活动id或活动类型为空");
        }
        PromotionPolymericResponse promotionPolymericResponse = new PromotionPolymericResponse();
        if (request.getPromotionType().equals(PromotionTypeEnum.Coupon.getCode())){
            // 优惠券
            CouponConfigQueryRequest couponConfigQueryRequest = new CouponConfigQueryRequest(){{
                setPromotionId(request.getPromotionId());
            }};
            CouponConfigQueryResponse couponConfigQueryResponse = baseActivityMapper.getCouponByPromotionId(couponConfigQueryRequest);
            if (couponConfigQueryResponse == null){
                log.error("查询活动为空，promotionId:{}",request.getPromotionId());
                return RestResult.error("9999","查询活动为空");
            }
            promotionPolymericResponse.setPromId(couponConfigQueryResponse.getPromotionId());
            promotionPolymericResponse.setPromName(couponConfigQueryResponse.getPromName());
            promotionPolymericResponse.setPromType(Integer.valueOf(couponConfigQueryResponse.getPromType()));
            promotionPolymericResponse.setDescription(couponConfigQueryResponse.getDescription());
            List<PromotionPolymericProductResponse> polymericProductResponses = couponGoodsMapper.queryPromotionPolyProductList(request);
            promotionPolymericResponse.setProductResponses(polymericProductResponses);
        }else {
            // 其他活动
            promotionPolymericResponse = promotionEntityMapper.queryPromotionPolyInfo(request);
            if (promotionPolymericResponse == null){
                log.error("查询活动为空，promotionId:{}",request.getPromotionId());
                return RestResult.error("9999","查询活动为空");
            }
            List<PromotionPolymericProductResponse> polymericProductResponses = promotionMerchantProductEntityMapper.queryPromotionPolyProductList(request);
            promotionPolymericResponse.setProductResponses(polymericProductResponses);
        }
        return RestResult.success(promotionPolymericResponse);
    }

    @Override
    public RestResult<PromotionSingleProductResponse> querySingleByMpId(PromotionPolymericRequest request) {

        PromotionSingleProductResponse response = promotionMerchantProductEntityMapper.querySingleByMpId(request);

        return RestResult.success(response);
    }

    @Override
    public RestResult<List<PromotionSingleProductResponse>> querySingleByMpIds(List<Long> mpIds) {

        List<PromotionSingleProductResponse> response = promotionMerchantProductEntityMapper.querySingleByMpIds(mpIds);

        return RestResult.success(response);
    }
}
